const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const User = require('../models/user');

// 欢迎页面
router.get('/', (req, res) => {
    res.render('index'); // 假设你的视图文件是 index.ejs
});

// 登录页面
router.get('/login', (req, res) => {
    res.render('login');
});

// 处理登录请求
router.post('/login', (req, res) => {
    const { username, password } = req.body;
    User.findByUsername(username, (err, user) => {
        if (err) return res.status(500).send('Error logging in');
        if (!user) return res.send('User not found');

        bcrypt.compare(password, user.password, (err, isMatch) => {
            if (err) return res.status(500).send('Error logging in');
            if (!isMatch) return res.send('Incorrect password');

            req.session.userId = user.id;
            res.redirect('/users');
        });
    });
});

// 注册页面
router.get('/register', (req, res) => {
    res.render('register');
});

// 处理注册请求
router.post('/register', (req, res) => {
    const { username, password, email } = req.body;
    User.create(username, password, email, (err) => {
        if (err) return res.status(500).send('Error registering user');
        res.redirect('/auth/login');
    });
});

module.exports = router;